<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Functions in Python</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Python, functions, tutorial, programming language, learn Python">
<meta name="description" content="In this chapter of the Python tutorial, we will
work with functions.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Functions in Python</h1>

<p>
In this part of the Python programming tutorial, we will talk about functions. 
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 

<p>
A function is a piece of code in a program. The function performs 
a specific task. The advantages of using functions are:
</p>

<ul>
    <li>Reducing duplication of code</li>
    <li>Decomposing complex problems into simpler pieces</li>
    <li>Improving clarity of the code</li>
    <li>Reuse of code</li>
    <li>Information hiding</li>
</ul>

<p>
Functions in Python are first-class citizens. It means that functions have equal
status with other objects in Python. Functions can be assigned to variables, 
stored in collections or passed as arguments. This brings additional flexibility
to the language.
</p>

<p>
There are two basic types of functions. Built-in functions and user 
defined ones. The built-in functions are part of the Python language. 
Examples are: <code>dir()</code>, <code>len()</code> or <code>abs()</code>.
The user defined functions are functions created with the <code>def</code> keyword. 
</p>


<h2>Defining functions</h2>

<p>
A function is created with the <code>def</code> keyword. The 
statements in the block of the function must be indented. 
</p>

<pre>
def function():
    pass
</pre>

<p>
The <code>def</code> keyword is followed by the function name with round brackets and a 
colon. The indented statements form a <i>body</i> of the function.
<p>

<p>
The function is later executed when needed. We say that we <i>call</i> the function. 
If we call a function, the  statements inside the function body are executed. 
They are not executed until the function is called.
</p>

<pre>
myfunc()
</pre>

<p>
To call a function, we specify the function name with the round brackets. 
</p>

<pre class="code">
#!/usr/bin/python

"""
The ret.py script shows how to work with
functions in Python. 
author: Jan Bodnar
ZetCode, 2011
"""


def showModuleName():
    print __doc__

def getModuleFile():
   return __file__

a = showModuleName()
b = getModuleFile()

print a, b
</pre>

<p>
The string at the top of the script is called the documentation string. 
It documents the current script. The file in which we put Python code 
is called a <i>module</i>. We define two functions. The 
first function will print the module doc string. The second will 
<code>return</code> the path of our module. Function may or 
may not return a value. If they explicitly do not return a value, they 
implicitly return <code>None</code>. The <code>__doc__</code> 
and <code>__file__</code> are special state attributes. 
Note, that there are two underscores on both sides of the attribute.
</p>

<pre>
$ ./ret.py 

The ret.py script shows how to work with
functions in Python. 
author: Jan Bodnar
ZetCode, 2011

None ./ret.py
</pre>

<hr class="btm">

<p>
Definitions of functions must precede their usage. Otherwise the
interpreter will complain with a <code>NameError</code>.
</p>

<pre class="code">
#!/usr/bin/python

def f1():
    print "f1()"
    
f1()
#f2()

def f2():
    print "f2()"
</pre>

<p>
In the above example we have two definitions of functions. 
One line is commented. Function call cannot be ahead of its
definition. 
</p>

<pre class="explanation">
#f2()

def f2():
    print "f2()"
</pre>

<p>
We can call the f2() only after its definition. Uncommenting
the line we get a <code>NameError</code>.
</p>


<h2>Where to define functions</h2>

<p>
Functions can be defined inside a module, a class or another
function. Function defined inside a class is called a <i>method</i>.
</p>

<pre class="code">
#!/usr/bin/python

class Some:

    @staticmethod  
    def f():
        print "f() method"

def f():
    print "f() function"
    
def g():
    def f():
        print "f() inner function"
    f()        
        
Some.f()
f()
g()
</pre>

<p>
In this example, we define an f() function in all possible 
places.
</p>

<pre class="explanation">
class Some:

    @staticmethod  
    def f():
        print "f() method"
</pre>

<p>
A static method is defined with a decorator in a Some class. 
</p>

<pre class="explanation">
def f():
    print "f() function"
</pre>

<p>
The function is defined in a module. 
</p>

<pre class="explanation">
def g():
    def f():
        print "f() inner function"
    f()   
</pre>

<p>
Here the f() function is defined inside another g() function. It is an inner 
function.
</p>

<pre class="explanation">
Some.f()
f()
g() 
</pre>

<p>
The static method is called by specifying the class name, the dot
operator and the function name with square brackets. Other functions
are called using their names and square brackets.
</p>

<pre>
$ ./defining.py
f() method
f() function
f() inner function
</pre>

<p>
Output.
</p>


<h2>Functions are objects</h2>

<p>
Functions in Python are objects. They can be manipulated like other objects
in Python. Therefore functions are called first-class citizens. This is not
true in other OOP languages like Java or C#.
</p>


<pre class="code">
#!/usr/bin/python

def f():
    """This function prints a message """
    print "Today it is a cloudy day"
    
print isinstance(f, object)
print id(f)
    
print f.func_doc
print f.func_name
</pre>

<p>
In this script we show, that our function is an object too.
</p>

<pre class="explanation">
def f():
    """This function prints a message """
    print "Today it is a cloudy day"
</pre>

<p>
We define an f() function. It prints a message to the console. It
has a documentation string. 
</p>

<pre class="explanation">
print isinstance(f, object)
</pre>

<p>
The <code>isinstance()</code> function checks, if the f() function is an instance
of the <code>object</code>. All objects in Python inherit from this base entity.
</p>

<pre class="explanation">
print id(f)
</pre>

<p>
Each object in Python has a unique id. The <code>id()</code> function returns
the object's id. 
</p>

<pre class="explanation">
print f.func_doc
print f.func_name
</pre>

<p>
Objects may have attributes. Here we print two attributes of the function.
</p>

<pre>
$ ./fobj.py
True
3077407212
This function prints a message 
f
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
Objects can be stored in collections and passed to functions. 
</p>

<pre class="code">
#!/usr/bin/python

def f():
    pass

def g():
    pass
  
def h(f):
    print id(f)
  
a = (f, g, h)

for i in a:
    print i
    
h(f)
h(g)
</pre>

<p>
We define three functions. We place them in a tuple and pass them 
to a function.
</p>

<pre class="explanation">
a = (f, g, h)

for i in a:
    print i
</pre>

<p>
We place three function objects in a tuple and traverse it with a for loop.
</p>

<pre class="explanation">
h(f)
h(g)
</pre>

<p>
We pass the f(), g() functions to the h() function. 
</p>

<pre>
$ ./fobj2.py
&lt;function f at 0xb7664fb4&gt;
&lt;function g at 0xb766c1b4&gt;
&lt;function h at 0xb766c3ac&gt;
3076935604
3076964788
</pre>

<p>
Output of the fobj.py script.
</p>


<h2>Three kinds of functions</h2>

<p>
Looking from a particular point of view, we can discern three kinds
of functions. Functions that are always available for usage, functions
that are contained within external modules, which must be imported and
functions defined by a programmer with the <code>def</code> keyword. 
</p>

<pre class="code">
#!/usr/bin/python

from math import sqrt

def cube(x):
    return x * x * x    
    
print abs(-1)
print cube(9)
print sqrt(81)
</pre>

<p>
Three kinds of functions are present in the above code. 
</p>

<pre class="explanation">
from math import sqrt
</pre>

<p>
The <code>sqrt()</code> function is imported from the math module. 
</p>

<pre class="explanation">
def cube(x):
    return x * x * x  
</pre>

<p>
The cube() function is a custom defined function. 
</p>

<pre class="explanation">
print abs(-1)
</pre>

<p>
The <code>abs()</code> function is a built-in function readily 
accessible. It is part of the core of the language. 
</p>


<h2>The return keyword</h2>

<p>
A function is created to do a specific task. Often there
is a result from such a task. The <code>return</code> keyword is 
used to return values from a function. A function may or may not return a value.
If a function does not have a return keyword, it will send
a <code>None</code> value. 
</p>

<pre class="code">
#!/usr/bin/python

def showMessage(msg):
    print msg

def cube(x):
    return x * x * x   
   
x = cube(3)    
print x

showMessage("Computation finished.")
print showMessage("Ready.")
</pre>

<p>
We have two functions defined. One uses the <code>return</code>
keyword, one does not. 
</p>

<pre class="explanation">
def showMessage(msg):
    print msg
</pre>

<p>
The showMessage() function does not return explicitly a value. It 
shows a message on the console. 
</p>

<pre class="explanation">
def cube(x):
    return x * x * x
</pre>

<p>
The cube() functions computes an expression and returns its
result with the <code>return</code> keyword. 
</p>

<pre class="explanation">
x = cube(3) 
</pre>

<p>
In this line we call the cube() function. The result of the computation
of the cube() function is returned and assigned to the x variable. 
It holds the result value now.
</p>

<pre class="explanation">
showMessage("Computation finished.")
</pre>

<p>
We call the showMessage() function with a message as a parameter. 
The message is printed to the console. We do not expect a value from 
this function.
</p>

<pre class="explanation">
print showMessage("Ready.")
</pre>

<p>
This code produces two lines. One is a message printed by the showMessage()
function. The other is the <code>None</code> value, which is implicitly sent
by functions without the <code>return</code> statement.
</p>

<pre>
$ ./return.py
27
Computation finished.
Ready.
None
</pre>

<p>
Example output.
</p>

<hr class="btm">

<p>
We can send more that one value from a function. The objects after the <code>return</code>
keyword are separated by commas. 
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 5]

def stats(x):
    mx = max(x)
    mn = min(x)
    ln = len(x)
    sm = sum(x)
    
    return mx, mn, ln, sm    
    
mx, mn, ln, sm = stats(n)
print stats(n)

print mx, mn, ln, sm
</pre>

<p>
There is a definition of a stats() function. This function
returns four values. 
</p>

<pre class="explanation">
return mx, mn, ln, sm
</pre>

<p>
The <code>return</code> keyword sends back four numbers. The 
numbers are separated by a comma character. In fact, we have sent
a tuple containing these four values. We could also return a list
instead of a tuple. 
</p>

<pre class="explanation">
mx, mn, ln, sm = stats(n)
</pre>

<p>
The returned values are assigned to local variables. 
</p>

<pre>
$ ./return2.py 
(5, 1, 5, 15)
5 1 5 15
</pre>

<p>
Output.
</p>


<h2>Function redefinition</h2>

<p>
Python is dynamic in nature. It is possible to redefine an already
defined function. 
</p>

<pre class="code">
#!/usr/bin/python

from time import gmtime, strftime


def showMessage(msg):
    print msg
        
showMessage("Ready.")

def showMessage(msg):
    print strftime("%H:%M:%S", gmtime()),
    print msg
    
showMessage("Processing.")  
</pre>

<p>
We define a showMessage() function. Later we provide a new definition of
the same function. 
</p>

<pre class="explanation">
from time import gmtime, strftime
</pre>

<p>
From the time module we import two functions which are used to 
compute the current time. 
</p>

<pre class="explanation">
def showMessage(msg):
    print msg        
</pre>

<p>
This is the first definition of a function. It only prints a message
to the console. 
</p>

<pre class="explanation">
def showMessage(msg):
    print strftime("%H:%M:%S", gmtime()),
    print msg
</pre>

<p>
Later in the source code, we set up a new definition of the showMessage()
function. The message is preceded with a timestamp. 
</p>

<pre>
$ ./redefinition.py
Ready.
23:49:33 Processing.
</pre>

<p>
Ouput of the script. 
</p>


<h2>Function arguments</h2>

<p>
Most functions accept arguments. Arguments are values, that are sent to 
the function. The functions process the values and optionally return 
some value back.
</p>

<pre class="code">
#!/usr/bin/python

def C2F(c):
    return c * 9/5 + 32

print C2F(100)
print C2F(0)
print C2F(30)
</pre>

<p>
In our example, we convert Celsius temperature to Fahrenheit. The C2F 
function accepts one argument c, which is the
Celsius temperature.
</p>

<pre>
$ ./fahrenheit.py 
212
32
86
</pre>

<p>
The arguments in Python functions may have implicit values. An implicit 
value is used, if no value is provided. 
</p>

<pre class="code">
#!/usr/bin/python

def power(x, y=2):
    r = 1
    for i in range(y):
       r = r * x
    return r

print power(3)
print power(3, 3)
print power(5, 5)
</pre>

<p>
Here we created a power function. The function has one argument with 
an implicit value. We can call the function with
one or two arguments. 
</p>

<pre>
$ ./power.py 
9
27
3125
</pre>

<p>
Python functions can specify their arguments with a keyword. This means, 
that when calling a function, we specify both a keyword and a value.
When we have multiple arguments and they are used without keywords, 
the order in which we pass those arguments is crucial.
If we expect a name, age, sex in a function without keywords, we cannot 
change their order. If we use keywords, we can. 
</p>

<pre class="code">
#!/usr/bin/python

def display(name, age, sex):
   print "Name: ", name
   print "Age: ", age
   print "Sex: ", sex


display("Lary", 43, "M")
display("Joan", 24, "F")
</pre>

<p>
In this example, the order in which we specify the arguments is important. 
Otherwise, we get incorrect results. 
</p>

<pre>
$ ./persons.py 
Name:  Lary
Age:  43
Sex:  M
Name:  Joan
Age:  24
Sex:  F
</pre>

<pre class="code">
#!/usr/bin/python

# person2.py

def display(name, age, sex):
   print "Name: ", name
   print "Age: ", age
   print "Sex: ", sex


display(age=43, name="Lary", sex="M")
display(name="Joan", age=24, sex="F")
</pre>

<p>
Now we call the functions with their keywords. The order may be changed, 
although it is not recommended to do so. Note, that we cannot use a 
non-keyword argument after a keyword argument. This would end in a syntax error. 
</p>

<pre>
display("Joan", sex="F", age=24)
</pre>

<p>
This is a legal construct. A non-keyword argument may be 
followed by keyword arguments. 
</p>

<pre>
display(age=24, name="Joan", "F")
</pre>

<p>
This will end in a syntax error. A non-keyword argument 
may not follow keyword arguments. 
</p>


<p>
Functions in Python can even accept arbitrary number of arguments. 
</p>

<pre class="code">
#!/usr/bin/python

def sum(*args):
   '''Function returns the sum 
   of all values'''
   r = 0
   for i in args:
      r += i
   return r


print sum.__doc__
print sum(1, 2, 3)
print sum(1, 2, 3, 4, 5)
</pre>

<p>
We use the <b>*</b> operator to indicate, that the function will accept 
arbitrary number of arguments. The sum() function will return the sum of 
all arguments. The first string in the function body is called the
function documentation string. It is used to document the function. 
The string must be in triple quotes. 
</p>

<pre>
$ ./summation.py 
Function returns the sum 
   of all values
6
15
</pre>

<p>
We can also use the <b>**</b> construct in our functions. In such a case, 
the function will accept a dictionary. The 
dictionary has arbitrary length. We can then normally parse the dictionary, as usual. 
</p>

<pre class="code">
#!/usr/bin/python

def display(**details):

   for i in details:
      print "%s: %s" % (i, details[i])


display(name="Lary", age=43, sex="M")
</pre>

<p>
This example demonstrates such a case. We can provide arbitrary number of 
key-value arguments. The function will handle them
all. 
</p>

<pre>
$ ./person.py 
age: 43
name: Lary
sex: M
</pre>


<h2>Passing by reference</h2>

<p>
Parameters to functions are passed by reference.
Some languages pass copies of the objects to functions.
Passing objects by reference has two important conclusions.
The process is faster than if copies of objects were passed.
Mutable objects that are modified in functions are permanently
changed. 
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 5]

print "Original list:", n

def f(x):
    x.pop()
    x.pop()
    x.insert(0, 0)
    print "Inside f():", x    
    
f(n)    

print "After function call:", n
</pre>

<p>
In our example, we pass a list of integers to a function. The
object is modified inside the body of the function. After
calling the function, the original object, the list of integers
is modified. 
</p>

<pre class="explanation">
def f(x):
    x.pop()
    x.pop()
    x.insert(0, 0)
    print "Inside f():", x  
</pre>

<p>
In the body of the function we work with the original object.
Not with a copy of the object. In many programming languages 
we woud receive a copy of an object by default. 
</p>


<pre>
$ ./byreference.py
Original list: [1, 2, 3, 4, 5]
Inside f(): [0, 1, 2, 3]
After function call: [0, 1, 2, 3]
</pre>

<p>
Once the list was modified it was modified for good.
</p>


<h2>Global and local variables</h2>

<p>
Next we will talk about how variables are used in Python functions. 
</p>

<pre class="code">
#!/usr/bin/python

name = "Jack"

def f():
   name = "Robert"
   print "Within function", name

print "Outside function", name
f()
</pre>

<p>
A variable defined in a function body has a <i>local</i> scope. It is 
valid only within the body of the function. 
</p>

<pre>
$ ./local.py 
Outside function Jack
Within function Robert
</pre>

<p>
Output.
</p>

<pre class="code">
#!/usr/bin/python

name = "Jack"

def f():
   print "Within function", name

print "Outside function", name
f()
</pre>

<p>
By default, we can get the contents of a <i>global</i> variable inside 
the body of a function.  But if we want to change a global variable in a 
function, we must use the <code>global</code>
keyword. 
</p>

<pre>
$ ./global.py 
Outside function Jack
Within function Jack
</pre>

<pre class="code">
#!/usr/bin/python

name = "Jack"

def f():
   global name 
   name = "Robert"
   print "Within function", name


print "Outside function", name
f()
print "Outside function", name
</pre>

<p>
Now, we will change the contents of a global name variable inside a function. 
</p>

<pre class="explanation">
global name 
name = "Robert"
</pre>

<p>
Using the <code>global</code> keyword, we reference the variable
defined outside the body of the function. The variable is given a
new value.
</p>

<pre>
$ ./global2.py 
Outside function Jack
Within function Robert
Outside function Robert
</pre>


<h2>Anonymous functions</h2>

<p>
It is possible to create anonymous functions in Python. Anonymous
functions do not have a name. With the <code>lambda</code> keyword,
little anonymous functions can be created. Anonymous functions are
also called lambda functions by Python programmers. They are part
of the functional paradigm incorporated in Python. 
</p>

<p>
Lambda functions are restricted to a single expression. They 
can be used wherever normal functions can be used. 
</p>

<pre class="code">
#!/usr/bin/python

y = 6

z = lambda x: x * y
print z(8)
</pre>

<p>
This is a small example of the lambda function. 
</p>

<pre class="explanation">
z = lambda x: x * y
</pre>

<p>
The <code>lambda</code> keyword creates an anonymous function. The x
is a parameter, that is passed to the lambda function. The parameter is
followed by a colon character. The code next to the colon is 
the expression that is executed, when the lambda function is called. 
The lambda function is assigned to the z variable. 
</p>

<pre class="explanation">
print z(8)
</pre>

<p>
The lambda function is executed. The number 8 is passed to the anonymous
function and it returns 48 as the result. Note that z is not a name for 
this function. It is only a variable to which the anonymous function
was assigned.
</p>

<pre>
$ ./lambda.py
48
</pre>

<p>
Output of the example. 
</p>

<hr class="btm">

<p>
The lambda function can be used elegantly with other functional
parts of the Python language, like <code>map()</code> or <code>filter()</code>
functions.
</p>

<pre class="code">
#!/usr/bin/python

cs = [-10, 0, 15, 30, 40]

ft = map(lambda t: (9.0/5)*t + 32, cs)
print ft
</pre>

<p>
In the example we have a list of celsius temperatures. We create a new
list containing temperatures in fahrenheit. 
</p>

<pre class="explanation">
ft = map(lambda t: (9.0/5)*t + 32, cs)
</pre>

<p>
The <code>map()</code> function applies the anonymous function
to each element of the cs list. It creates a new ft list containing
the computed fahrenheit temperatures.
</p>

<pre>
$ ./lambda2.py
[14.0, 32.0, 59.0, 86.0, 104.0]
</pre>

<p>
Example output.
</p>


<p>
This chapter was about functions in Python.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 21, 2012  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

